package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.service.ICartService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ClassName: ICartServiceImpl
 * @Description: TODO 购物车服务的实现
 * @Author:zk
 * @Date: 2022/5/19 16:43
 * @Version: 1.0
 **/
@Slf4j
@Service
public class ICartServiceImpl implements ICartService {
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    ItemMapper itemMapper;

    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse cartListByIdResponse = new CartListByIdResponse();
        try{
            if (request.getUserId()==null){
                throw new ValidateException(ShoppingRetCode.REQUISITE_PARAMETER_NOT_EXIST.getCode()
                ,ShoppingRetCode.REQUISITE_PARAMETER_NOT_EXIST.getMessage());
            }

            Map<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());

            List<CartProductDto> cartProductDtos = new ArrayList<>();


            for (Map.Entry<Long,CartProductDto> entry:map.entrySet()){

                CartProductDto value = entry.getValue();

                cartProductDtos.add(value);
            }

            cartListByIdResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            cartListByIdResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            cartListByIdResponse.setCartProductDtos(cartProductDtos);

        }catch (ValidateException e){
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(cartListByIdResponse, e);
        }
        return cartListByIdResponse;
    }


    /**
     * @author: zk
     * @description: TODO  添加商品至购物车(默认为选中状态)
     * @date: 2022/5/19 22:45
     */
    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse addCartResponse = new AddCartResponse();
        try {
            request.requestCheck();
            Map<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
            Long itemId = request.getItemId();
            Item item = itemMapper.selectByPrimaryKey(itemId);

            CartProductDto cartProductDto = CartItemConverter.item2Dto(item);


            //若该商品已存在于购物车,则叠加数量即可
            if (map.get(itemId) != null) {
                CartProductDto dto = map.get(itemId);
                dto.setProductNum(dto.getProductNum() + request.getNum());
                //添加后变为选中状态
                dto.setChecked("true");

                map.put(itemId, dto);
            }else{
                //添加至购物车的商品初始默认选中
                cartProductDto.setChecked("true");
                cartProductDto.setProductNum(request.getNum().longValue());
//                cartProductDto.setAddTime(System.currentTimeMillis());
                //添加商品
                map.put(itemId, cartProductDto);
            }



            addCartResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            addCartResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            //测试添加
            CartProductDto r = map.get(itemId);
            System.out.println("已添加至购物车:  商品名称(id):" + r.getProductName() + "[" + r.getProductId() + "]     " + "商品数量:" + r.getProductNum());
        }catch (ValidateException e){
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(addCartResponse, e);
        }

        return  addCartResponse;
    }


    /**
     * @author: zk
     * @description: TODO  更新购物车中商品(redis数据库操作)
     * @date: 2022/5/19 17:04
     */
    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        Map<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
        Long itemId = request.getItemId();
        Item item = itemMapper.selectByPrimaryKey(itemId);
        if (item==null){
            throw new ValidateException(SysRetCodeConstants.DATA_NOT_EXIST.getCode(),SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
        }
        CartProductDto cartProductDto = CartItemConverter.item2Dto(item);

        cartProductDto.setProductNum(request.getNum().longValue());
        cartProductDto.setChecked(request.getChecked());
        //修改redis中对应购物车中的对应商品数量及其选中状态
        map.put(itemId,cartProductDto);


        //测试取出
        CartProductDto r = map.get(itemId);
        System.out.println("商品名称(id):"+r.getProductName()+"["+r.getProductId()+"]     "+"商品数量:"+r.getProductNum()+"    是否选中:"+r.getChecked());
        return new UpdateCartNumResponse();
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        Map<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
        for (Map.Entry<Long,CartProductDto> entry:map.entrySet()){
            Long key = entry.getKey();
            CartProductDto value = entry.getValue();
            value.setChecked("true");

            map.put(key,value);
        }
        return new CheckAllItemResponse();
    }

    /**
     * @author: zk
     * @description: TODO 删除购物车中的商品
     * @date: 2022/5/19 20:48
     */
    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        Map<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
        if (map==null||map.get(request.getItemId())==null){
            throw new ValidateException(SysRetCodeConstants.DATA_NOT_EXIST.getCode(),SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
        }
        map.remove(request.getItemId());
        return new DeleteCartItemResponse();

    }

    /**
     * @author: zk
     * @description: TODO 删除购物车中选中的商品
     * @date: 2022/5/19 22:02
     */
    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        Map<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
        //获取该用户购物车的所有商品信息
        for (Map.Entry<Long,CartProductDto> entry:map.entrySet()){
            if (entry.getValue().getChecked().equals("true")){
                map.remove(entry.getKey());
            }
        }
        return new DeleteCheckedItemResposne();
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        ClearCartItemResponse clearCartItemResponse = new ClearCartItemResponse();
        try{
            request.requestCheck();
            Map<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());
            List<Long> productIds = request.getProductIds();
            for (Long productId : productIds) {
                map.remove(productId);
            }
            clearCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            clearCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(clearCartItemResponse, e);
        }
        return clearCartItemResponse;

    }
}
